//
//  HPSearchView.swift
//  MyWeibo
//
//  Created by Apeng on 16/4/7.
//  Copyright © 2016年 Apengpeng. All rights reserved.
//

import UIKit

class HPSearchView: UIView {

    @IBOutlet weak var textField: UITextField!
    
    @IBOutlet weak var cancelBtn: UIButton!
    
    @IBOutlet weak var rightDistance: NSLayoutConstraint!
   // 通过xib加载需要设置大小
    override func awakeFromNib() {

        self.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.size.width, height: frame.height)
        
        // 设置文本框左边的图片
        textField.leftView = UIImageView(image: UIImage(named: "tabbar_discover"))
        // 设置左边的显示图片模式
        textField.leftViewMode = UITextFieldViewMode.Always
        // 设置frame
        textField.frame = CGRectMake(0, 0, textField.frame.size.height, textField.frame.size.height)
        // 设置填充模式
        textField.leftView?.contentMode = .Center
//        textField.leftView?.contentMode = UIViewContentMode.ScaleAspectFit
//        textField.leftView?.contentMode = UIViewContentMode.ScaleAspectFill
        
        
        // 设置textField 的圆角
//        textField.layer.cornerRadius = 15 
//        textField.layer.masksToBounds = true
//        textField.layer.borderColor = UIColor.orangeColor().CGColor
//        textField.layer.borderWidth = 2.0
        // 设置阴影
//        textField.layer.shadowRadius = 15
//        textField.layer.shadowOpacity = 1.0
//        textField.layer.shadowColor = UIColor.greenColor().CGColor
//        textField.layer.shadowOffset = CGSize(width: -5.0, height: -5.0)
        
        
    }
    
    
    // 提供类方法加载searchView
    class func loadSearchView() -> HPSearchView {
        let searchView = NSBundle.mainBundle().loadNibNamed("HPSearchView", owner: nil, options: nil).last as! HPSearchView // 必选包, 指定类型
        
        return searchView
    }
    
    
    // MARK: 文本框中的值变化时, 按钮显示
    @IBAction func textFieldValueChanged(sender: AnyObject) {
        
        // 当有值时
        rightDistance.constant = cancelBtn.frame.size.width + 5
        
        // 强制刷新页面
        UIView.animateWithDuration(0.25) { () -> Void in
            // view 调用执行
            self.layoutIfNeeded()
        }
    }
    
    
    // 给按钮添加点击事件
    @IBAction func cancelBtnDidClick(sender: AnyObject) {
        
        rightDistance.constant = 0
        // 强制刷新页面
        UIView.animateWithDuration(0.25) { () -> Void in
            self.layoutIfNeeded()
            
            // 收回键盘
//            self.textField.resignFirstResponder()
            self.textField.endEditing(true)
        }
    }
    
    
}
